package etc

import (
	"github.com/beego/beego/v2/core/logs"
	"gopkg.in/yaml.v2"
	"io/ioutil"
)

type (
	Freeswitch struct {
		Addr    string `yaml:"addr"`
		Domain  string `yaml:"domain"`
		Passwd  string `yaml:"pwd"`
		AcctDir string `yaml:"direct"`
	}

	MysqlDB struct {
		Name     string `yaml:"name"`
		IP       string `yaml:"ip"`
		Port     int    `yaml:"port"`
		Db       string `yaml:"db"`
		User     string `yaml:"user"`
		Password string `yaml:"password"`
	}

	Mysql struct {
		Debug    bool    `yaml:"debug"`
		MysqlDBs MysqlDB `yaml:"mysql_dbs"`
	}

	Redis struct {
		IP       string `yaml:"ip"`
		Password string `yaml:"password"`
	}

	common struct {
		Dsid     int    `yaml:"dsid"`
		CallBack string `yaml:"callback"`
		Host     string `yaml:"host"`
		Media    string `yaml:"mediaDir"`
		Record   string `yaml:"recordDir"`
		TtsPath  string `yaml:"ttsPath"`
	}

	test struct {
		Caller string `yaml:"caller"`
		Callee string `yaml:"callee"`
		Number int    `yaml:"number"`
	}

	prefixInfo struct {
		Verify   string `yaml:"verify"`
		Notify   string `yaml:"notify"`
		CallBack string `yaml:"callback"`
	}

	vos struct {
		Addr       string     `yaml:"addr"`
		NeedPrefxi bool       `yaml:"needPrefix"`
		Prefix     prefixInfo `yaml:"prefix"`
	}

	oss struct {
		EndPoint   string `yaml:"endPoint"`
		Bucket     string `yaml:"bucket"`
		SecretId   string `yaml:"secretId"`
		SecretKey  string `yaml:"secretKey"`
		UploadTask int    `yaml:"taskNum"`
	}

	config struct {
		Fs      Freeswitch `yaml:"freeswitch"`
		Mysql   Mysql      `yaml:"mysql"`
		Test    test       `yaml:"test"`
		Vos     vos        `yaml:"vos"`
		Storage oss        `yaml:"oss"`
		Redis   Redis      `yaml:"redis"`
		Base    common     `yaml:"common"`
	}
)

var Conf config

func GetRecordDir() string {
	return Conf.Base.Record
}

// 初始化配置文件
func InitConfig(file string) error {

	bs, err := ioutil.ReadFile(file)
	if err != nil {
		return err
	}

	return yaml.Unmarshal(bs, &Conf)
}

// 初始化配置
func InitConfigFromData(data []byte) error {

	return yaml.Unmarshal(data, &Conf)

}

// 初始化配置
func UpdateConfigFromData(data []byte) {

	newConf := config{}
	err := yaml.Unmarshal(data, &newConf)
	if err != nil {
		logs.Error("解析配置文件失败:%v", err)
		return
	}

	if newConf.Fs != Conf.Fs {
		logs.Debug("freeswitch 配置变更")
	}

	if newConf.Base != Conf.Base {
		logs.Debug("Base 配置变更")
	}

	if newConf.Mysql != Conf.Mysql {
		logs.Debug("Mysql 配置变更,Old:%v,新配置:%v", Conf.Mysql, newConf.Mysql)
	}

	if newConf.Redis != Conf.Redis {
		logs.Debug("Redis 配置变更")
	}

	if newConf.Storage != Conf.Storage {
		logs.Debug("Storage 配置变更")
	}

	if newConf.Vos != Conf.Vos {
		logs.Debug("Vos 配置变更")
	}

	if newConf.Test != Conf.Test {
		logs.Debug("Test 配置变更")
	}

}
